import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';

import { DataTablesComponent, DataTablesComponentConfig } from 'app/theme/components/dataTables';

import { NotificationListService } from './notification-list.service';
import { SearchForm } from './search-form.class';

@Component({
  selector: 'notification-list',
  templateUrl: 'notification-list.component.html',
  styleUrls: ['notification-list.component.scss'],
  // encapsulation: ViewEncapsulation.None
})
export class NotificationListComponent implements OnInit {
  public dataTablesConfig: DataTablesComponentConfig = new DataTablesComponentConfig();
  public disableReviewBtn: boolean = true;
  public disableDeleteBtn: boolean = true;
  public searchForm: SearchForm = new SearchForm();
  @ViewChild(DataTablesComponent) dataTable: DataTablesComponent;
  private notificationTableUrl: string = '/water/boards';
  private selectedRowData: any[];
  private errorShow = false;

  constructor(private notificationListService: NotificationListService) {
  }

  ngOnInit() {
    this.dataTablesConfig.ajaxUrl = this.notificationTableUrl;
    this.dataTablesConfig.columnsDef = [
      {'name': '标题', 'id': 'title'},
      {'name': '发布时间', 'id': 'createtime'}
    ];
  }

  tableRowSelect(rowData: any[]) {
    this.disableAllButtons();
    this.disableReviewBtn = rowData.length !== 1;
    this.disableDeleteBtn = rowData.length === 0;

    this.selectedRowData = rowData;
  }

  handleError(e:any){
    if(e.type == 'error'){
      this.errorShow = true;
    }
  }

  private disableAllButtons() {
    this.disableReviewBtn = this.disableDeleteBtn = true;
  }

  deleteNotification() {
    let idArr: string[] = [];

    for (let index = 0; index < this.selectedRowData.length; index++) {
      let row = this.selectedRowData[index];
      idArr.push(row.ids);
    }

    this.notificationListService.deleteNotification(idArr).then(resp => {
      if (resp.status === 'success') {
        this.dataTable.draw();
      }
    });
  }

  updateDateRange(event) {
    this.searchForm.startdate = this.date2String(event.beginDate);
    this.searchForm.enddate = this.date2String(event.endDate);
  }

  search() {
    this.dataTable.draw();
  }

  private date2String(date: any): string {
    if (Object.keys(date).length === 0 || date === null || date === undefined || (date.year == 0&&date.month==0&&date.day==0)) {
      return null;
    }

    let str = date.year + '-';
    if (date.month < 10) {
      str += '0';
    }
    str += date.month + '-';

    if (date.day < 10) {
      str += '0';
    }
    str += date.day;
    return str;
  }
}
